package com.daykw.wkinfo.task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daykw.wkinfo.config.NutzDaoConfig;
import com.daykw.wkinfo.http.HttpBase;
import com.daykw.wkinfo.model.ArticleTask;
import com.daykw.wkinfo.model.DatePageTask;
import com.daykw.wkinfo.model.DateSearchTask;
import com.daykw.wkinfo.utils.SpringContextHolder;


public class DateTypeJob implements Runnable {

	private static Logger logger = Logger.getLogger(DateTypeJob.class);
	private SimpleDateFormat ft = new SimpleDateFormat("yyyy.MM.dd");
	private SimpleDateFormat old = new SimpleDateFormat("yyyyMMdd");

	@Override
	public void run() {
		rest();
	}
	private void rest() {
		NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Accept", "application/json, text/plain, */*");
		headers.put("Accept-Encoding", "gzip, deflate");
		headers.put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
		headers.put("Appversion", "1.0.0");
		headers.put("Cache-Control", "no-cache");
		headers.put("Content-Type", "application/json;charset=UTF-8");
		headers.put("Cookie",
				"connect.sid=s%3ABolr-8MgBBLElSI1CTvnmJ_hN5T9c704.JujaOWontzr6nRkdM9dT6%2F2qIhqVp6958K83%2Bc14KjA; UM_distinctid=165389d414c617-08c7284297a47b-37664109-11cc40-165389d414d39a; CNZZDATA1261306096=306951218-1534251672-%7C1534251672; Hm_lvt_fecce484974a74c6d10f421b6d3bd395=1534253155; CCKF_visitor_id_100847=1114575298; cckf_track_100847_AutoInviteNumber=0; cckf_track_100847_ManualInviteNumber=0; userConfig=%7B%22moduleList%22%3A%5B%5D%2C%22userStaffType%22%3A0%2C%22isIpUser%22%3A0%2C%22parentId%22%3A0%2C%22sourceSiteUrl%22%3Anull%2C%22sourceSiteName%22%3Anull%2C%22clientSource%22%3A%22alphalawyerkhly%22%2C%22trial%22%3Afalse%2C%22expire%22%3Afalse%7D; autologin=true; username=alphalawyer; userInfo=%7B%22id%22%3A%22%22%2C%22username%22%3A%22alphalawyer%22%2C%22password%22%3A%220x01000000142820f4a8cdf13edd1700122e8791177f724cd35b95c1201f795273e9d61059dd22c8d924e788d2%22%2C%22email%22%3A%22alphalawyer%40fsoo.com%22%2C%22userLang%22%3A%22cn%22%2C%22userPageSize%22%3A100%2C%22isSend%22%3Atrue%2C%22sendLang%22%3A%22cn%22%2C%22recieveEmails%22%3A%5B%5D%2C%22userType%22%3A%22normal%22%2C%22groupName%22%3A%22law%22%2C%22libraryCode%22%3A%22%22%2C%22licences%22%3A400%2C%22telephone%22%3A%221000070349%22%2C%22conf%22%3A%22%7B%5C%22legislationViewType%5C%22%3A%5C%22group%5C%22%2C%5C%22lawExpressViewType%5C%22%3A%5C%22group%5C%22%2C%5C%22mLegislationViewType%5C%22%3A%5C%22list%5C%22%2C%5C%22mLawExpressViewType%5C%22%3A%5C%22list%5C%22%7D%22%7D; loginId=06e14e93566348908eb2a315fc27f3f1; Hm_lpvt_fecce484974a74c6d10f421b6d3bd395=1534253248; cckf_track_100847_LastActiveTime=1534253249");headers.put("Host", "law.wkinfo.com.cn.");
		headers.put("Host", "law.wkinfo.com.cn.");
		headers.put("Identification", "_4ea3ef209ad811e8ab2a890a59517782");
		headers.put("Origin", "http://law.wkinfo.com.cn.");
		headers.put("Referer", "https://law.wkinfo.com.cn/legislation/list?mode=advanced");
		headers.put("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
		headers.put("X-Tingyun-Id", "tN6Win9ZeY4;r=11995442");
		
		
		List<DateSearchTask> ds =	dao.query(DateSearchTask.class, Cnd.where("status", "=", 3));
		
		for(DateSearchTask t:ds) {
			Date ss = null;
			Date ee = null;
			try {
				ss = ft.parse(t.getStart());
				ee = ft.parse(t.getEnd());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			int start = Integer.parseInt(old.format(ss));
			int end = Integer.parseInt(old.format(ee));
			this.getSeartEndTask(start, end, dao, headers);
			dao.update(DateSearchTask.class, Chain.make("status", 5),
					Cnd.where("id", "=", t.getId()));
			logger.info("###########"+t.getStart()+"---"+t.getEnd()+"######完成");
		}
		
	}

	private void init() {
		NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);

		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Accept", "application/json, text/plain, */*");
		headers.put("Accept-Encoding", "gzip, deflate");
		headers.put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
		headers.put("Appversion", "1.0.0");
		headers.put("Cache-Control", "no-cache");
		headers.put("Content-Type", "application/json;charset=UTF-8");
		headers.put("Cookie",
				"connect.sid=s%3ABolr-8MgBBLElSI1CTvnmJ_hN5T9c704.JujaOWontzr6nRkdM9dT6%2F2qIhqVp6958K83%2Bc14KjA; UM_distinctid=165389d414c617-08c7284297a47b-37664109-11cc40-165389d414d39a; CNZZDATA1261306096=306951218-1534251672-%7C1534251672; Hm_lvt_fecce484974a74c6d10f421b6d3bd395=1534253155; CCKF_visitor_id_100847=1114575298; cckf_track_100847_AutoInviteNumber=0; cckf_track_100847_ManualInviteNumber=0; userConfig=%7B%22moduleList%22%3A%5B%5D%2C%22userStaffType%22%3A0%2C%22isIpUser%22%3A0%2C%22parentId%22%3A0%2C%22sourceSiteUrl%22%3Anull%2C%22sourceSiteName%22%3Anull%2C%22clientSource%22%3A%22alphalawyerkhly%22%2C%22trial%22%3Afalse%2C%22expire%22%3Afalse%7D; autologin=true; username=alphalawyer; userInfo=%7B%22id%22%3A%22%22%2C%22username%22%3A%22alphalawyer%22%2C%22password%22%3A%220x01000000142820f4a8cdf13edd1700122e8791177f724cd35b95c1201f795273e9d61059dd22c8d924e788d2%22%2C%22email%22%3A%22alphalawyer%40fsoo.com%22%2C%22userLang%22%3A%22cn%22%2C%22userPageSize%22%3A100%2C%22isSend%22%3Atrue%2C%22sendLang%22%3A%22cn%22%2C%22recieveEmails%22%3A%5B%5D%2C%22userType%22%3A%22normal%22%2C%22groupName%22%3A%22law%22%2C%22libraryCode%22%3A%22%22%2C%22licences%22%3A400%2C%22telephone%22%3A%221000070349%22%2C%22conf%22%3A%22%7B%5C%22legislationViewType%5C%22%3A%5C%22group%5C%22%2C%5C%22lawExpressViewType%5C%22%3A%5C%22group%5C%22%2C%5C%22mLegislationViewType%5C%22%3A%5C%22list%5C%22%2C%5C%22mLawExpressViewType%5C%22%3A%5C%22list%5C%22%7D%22%7D; loginId=06e14e93566348908eb2a315fc27f3f1; Hm_lpvt_fecce484974a74c6d10f421b6d3bd395=1534253248; cckf_track_100847_LastActiveTime=1534253249");headers.put("Host", "law.wkinfo.com.cn.");
		headers.put("Identification", "_4ea3ef209ad811e8ab2a890a59517782");
		headers.put("Origin", "http://law.wkinfo.com.cn.");
		headers.put("Referer", "https://law.wkinfo.com.cn/legislation/list?mode=advanced");
		headers.put("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
		headers.put("X-Tingyun-Id", "tN6Win9ZeY4;r=11995442");

		int start = 19900101;
		int end = 20180831;
		try {

			this.getSeartEndTask(start, end, dao, headers);
		
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	private void getSeartEndTask(int start, int end, NutDao dao, Map<String, String> headers) {
		try {
			Thread.sleep(1000);
			int dif = end - start;
			Date s1 = old.parse(start + "");
			Date e1 = old.parse(end + "");

			String s2 = ft.format(s1);
			String e2 = ft.format(e1);
			HttpBase http = new HttpBase();
			String url = "http://law.wkinfo.com.cn./csi/search";

			String body = "{\"indexId\":\"law.legislation\",\"query\":{\"queryString\":\"*:*\",\"filterQueries\":[\"defaultRangeDoc:1\"],\"filterDates\":[\"promulgatingDate:["
					+ s2 + " TO " + e2
					+ "]\"]},\"searchScope\":{\"treeNodeIds\":[]},\"relatedIndexQueries\":[],\"sortOrderList\":[{\"sortKey\":\"important\",\"sortDirection\":\"ASC\"},{\"sortKey\":\"promulgatingDate\",\"sortDirection\":\"DESC\"}],\"pageInfo\":{\"limit\":6,\"offset\":0},\"otherOptions\":{\"requireLanguage\":\"cn\",\"relatedIndexEnabled\":true,\"groupEnabled\":true,\"smartEnabled\":true,\"buy\":false,\"summaryLengthLimit\":100,\"advanced\":true,\"synonymEnabled\":true,\"isHideBigLib\":0},\"chargingInfo\":{\"useBalance\":true}}";
			String html = null;
			try {
				html = http.post(url, "utf-8", headers, body,true);
			} catch (Exception e) {
				
				try {
					html = http.post(url, "utf-8", headers, body,true);
				}catch(Exception ee) {
					DateSearchTask search = new DateSearchTask();
					search.setCreate_time(new Date());
					search.setStart(s2);
					search.setEnd(e2);
					search.setPage(1);
					search.setRetcount(-1);

					search.setStatus(3);
					try {
						dao.fastInsert(search);
					} catch (Exception e11) {
						logger.error("请求下載錯誤,date" + s2 + "-" + e2);
					}
					return;
				}
				
				
				
			}

			logger.info(html);
			JSONObject json = (JSONObject) JSONObject.parse(html);
			if (json != null) {
				JSONObject searchMetadata = json.getJSONObject("searchMetadata");
				int docCount = searchMetadata.getIntValue("docCount");
				if (docCount <= 4000) {
					DateSearchTask search = new DateSearchTask();
					search.setCreate_time(new Date());
					search.setStart(s2);
					search.setEnd(e2);
					search.setPage(1);
					search.setRetcount(docCount);

					search.setStatus(0);
					try {
						dao.fastInsert(search);
					} catch (Exception e) {

						dao.update(DateSearchTask.class, Chain.make("retcount", docCount).add("status", 0),
								Cnd.where("start", "=", s2).and("end", "=", e2));

						logger.error("更新,date" + s2 + "-" + e2);
					}
					JSONArray resultGroups = json.getJSONArray("resultGroups");
					for (int i = 0; i < resultGroups.size(); i++) {
						JSONObject j = resultGroups.getJSONObject(i);
						JSONObject groupMetadata = j.getJSONObject("groupMetadata");
						String gid = groupMetadata.getString("groupId");
						String gname = groupMetadata.getString("title");
						int retCount = groupMetadata.getIntValue("resultCount");
						JSONArray documentList = j.getJSONArray("documentList");
						DatePageTask page = new DatePageTask();
						page.setCreate_time(new Date());
						page.setStart(s2);
						page.setEnd(e2);
						page.setPage(1);
						page.setRetcount(retCount);

						page.setGroupname(gname);
						page.setGroupid(gid);

						if (retCount > 6) {
							page.setStatus(0);
						} else {
							for (int k = 0; k < documentList.size(); k++) {
								JSONObject doc = documentList.getJSONObject(k);
								String docId = doc.getString("docId");
								String title = doc.getString("title");

							

								ArticleTask a = dao.fetch(ArticleTask.class, Cnd.where("aid", "=", docId));
								if (a != null) {
									dao.update(ArticleTask.class,
											Chain.make("title", title).add("prop", doc.toJSONString()),
											Cnd.where("aid", "=", docId));
								} else {
									a = new ArticleTask();
									a.setAid(docId);

									a.setTitle(title);
									a.setSource(0);

									a.setUrl("https://law.wkinfo.com.cn/legislation/detail/" + docId);
									a.setCreate_time(new Date());
									a.setProp( doc.toJSONString());
									a.setStatus(0);
									try {
										dao.fastInsert(a);
									} catch (Exception e) {
										e.printStackTrace();
									}
								}

							}

							page.setStatus(1);
						}

						try {
							dao.fastInsert(page);
						} catch (Exception e) {
							logger.error("重複下載,group" + gname);
						}
					}
				} else {
					dif = dif / 2;

					this.getSeartEndTask(start, start + dif, dao, headers);
					this.getSeartEndTask(start + dif, end, dao, headers);
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		}

	}

}
